package com.learn.service.impl;

import com.learn.mapper.AuthCodeMapper;
import com.learn.pojo.AuthCode;
import com.learn.service.AuthCodeService;
import com.learn.service.SendEmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @program: learn-parent
 * @description
 * @author: luffy
 * @create: 2020-09-16 11:09
 */
@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    @Autowired
    private AuthCodeMapper authCodeMapper;

    @Reference
    private SendEmailService sendEmailService;

    @Override
    public boolean createAuthCode(String email) {
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        Date createTime = new Date();
        Date expireTime = new Date();
        expireTime.setTime(createTime.getTime() + (10 * 60 * 1000));
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(expireTime);
        System.out.println(createTime + "=======>" + expireTime);
        try {
            authCodeMapper.createAuthCode(email, code, createTime, expireTime);
            sendEmailService.sendEmail(email, code);

        } catch (Exception e) {
            System.out.println("数据异常");
            return false;
        }
        return true;

    }

    @Override
    public Integer validateAuthCode(String email, String code) {
        List<AuthCode> codeList = authCodeMapper.getAuthCodeByEmail(email);
        int index = codeList.size() - 1;
        AuthCode authCode = codeList.get(index);
        Date expireTime = authCode.getExpireTime();
        if (expireTime.getTime() > System.currentTimeMillis()) {
            if (authCode.getCode().equals(code)) {
                return 0;
            }
            return 1;
        } else {
            return 2;
        }
    }

}
